package com.gongpingjialoan.activity.sell;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.car.FreeSellAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AssessHistory;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.network.NetDataJson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/11.
 */
public class FreeSellCarActivity extends BaseActivity implements AbsListView.OnItemClickListener, NetDataJson.OnNetDataJsonListener,
        PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private PullToRefreshListView pullToRefreshListView;

    private ListView listView;

    private int pageIndex;

    private boolean isLoadingMore;

    private boolean hasMore;

    private NetDataJson netWork;

    private boolean isRefresh = true;

    private View footView, headView;

    private ImageView no_info;

    private FreeSellAdapter mFreeSellAdapter;

    private List<AssessHistory> mAssessHistories;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "sell_evalHistory";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.free_sell_car);
        setTitle("估值历史");
        initView();
    }


    private void initView() {

        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        headView = LayoutInflater.from(this).inflate(R.layout.free_sell_head, null);
        mAssessHistories = new ArrayList<>();
        no_info = (ImageView) findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        listView = pullToRefreshListView.getRefreshableView();
        pageIndex = 1;
        isLoadingMore = true;
        hasMore = true;
        mFreeSellAdapter = new FreeSellAdapter(this, mAssessHistories);
        listView.addHeaderView(headView);
        listView.addFooterView(footView);
        listView.setOnItemClickListener(this);
        listView.setAdapter(mFreeSellAdapter);
        listView.removeHeaderView(headView);
        listView.removeFooterView(footView);
        listView.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 200);
    }

    private void refresh() {
        no_info.setVisibility(View.GONE);
        isRefresh = true;
        pageIndex = 1;
        hasMore = true;
        updateData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (netWork != null) {
            netWork.cancelTask();
            netWork = null;
        }
    }

    private void updateData() {
        if (netWork == null) {
            netWork = new NetDataJson(this);
        }
        netWork.addParam("page", pageIndex);
        netWork.addParam("record_type", "eval_sell");
        netWork.setUrl(API.collectHistory);
        netWork.request("get");
    }


    // 加载更多
    private void LoadMoreData() {
        if (!hasMore) {
            Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isLoadingMore && hasMore && mAssessHistories.size() > 0) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            isLoadingMore = true;
            pageIndex++;
            updateData();
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(position == 0 || position == 1 ) return;
        AssessHistory assessHistory = (AssessHistory) view.getTag(R.id.tag_second);
        AssessmentData data = AssessmentData.getInstance();
        data.clear();
        data.setBrandName(assessHistory.brand);
        data.setBrandSlug(assessHistory.brand_slug);
        data.setMile(assessHistory.mile);
        data.setModelDetailName(assessHistory.getModel_detail());
        data.setModelDetailSlug(assessHistory.getModel_detail_slug());
        data.setModelName(assessHistory.getModel());
        data.setModelSlug(assessHistory.getModel_slug());
        data.setModelThumbnail(assessHistory.url);
        data.setMonth(assessHistory.month + "");
        data.setYear(assessHistory.year + "");
        data.setCity(assessHistory.city);
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onLastItemVisible() {
        LoadMoreData();
    }



//    private  void  gotoSellCar(){
//        Intent intent = new Intent(this, WantSellCarActivity.class);
//        intent.putExtra("from", "no_auto_sell");
//        startActivity(intent);
//        finish();
//    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        isLoadingMore = false;
        pullToRefreshListView.onRefreshComplete();
//        gotoSellCar();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        pullToRefreshListView.onRefreshComplete();
        JSONArray jsonArray = null;
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        if (isRefresh) {
            mAssessHistories.clear();
        }
        try {
            jsonArray = json.getJSONArray("records");
            if (0 == jsonArray.length()) {
//                gotoSellCar();
                isLoadingMore = false;
                no_info.setVisibility(View.VISIBLE);
                return;
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                AssessHistory ah = new AssessHistory();
                JSONObject object = jsonArray.getJSONObject(i);
                ah.model_detail = object.getString("model_detail");
                ah.city = object.getString("city");
                ah.model_slug = object.getString("model_slug");
                ah.brand = object.getString("brand");
                ah.month = object.getString("month");
                ah.model_detail_slug = object.getString("model_detail_slug");
                ah.mile = object.getString("mile");
                ah.create_time = object.getString("create_time");
                ah.pricetype = object.getString("pricetype");
                ah.eval_price = object.getString("eval_price");
                ah.year = object.getString("year");
                ah.brand_slug = object.getString("brand_slug");
                ah.model = object.getString("model");
                ah.url = object.getString("thumbnail");
                ah.condition = object.getString("condition");
                ah.record_id = object.getString("record_id");
                mAssessHistories.add(ah);
            }
            int page_num = json.getInt("total_page");
            if (page_num == pageIndex) {
                hasMore = false;
            }
        } catch (JSONException e) {
//            gotoSellCar();
            isLoadingMore = false;
            return;
        }
        isLoadingMore = false;
        if (listView.getHeaderViewsCount() == 1)
            listView.addHeaderView(headView);
        mFreeSellAdapter.setData(mAssessHistories);

    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }


    public void sellCar(View view) {
        Intent intent = new Intent(this, WantSellCarActivity.class);
        intent.putExtra("from", "no_auto_sell");
        startActivity(intent);
        finish();
    }

}
